<?php

namespace App\Jobs;

use App\Models\Mint;
use App\Models\Nft;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class MintJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(public Nft $nft)
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $exists = Mint::where('nft_id', $this->nft->nft_id)->whereDate('created_at', today())->exists();
        if ($exists) {
            return;
        }
        if ($this->nft->days <= $this->nft->minted_days) {
            return;
        }
        $per_mint = Setting::where('key', 'per_mint')->value('value');
        //产币数量
        $amount = bcmul($this->nft->power, $per_mint, 8);
        //转账手续费
        $fee = Setting::where('key', 'transfer_fee')->value('value');
        //实际应转出数量
        $to_amount = bcsub($amount, $fee, 8);

        DB::transaction(function () use ($per_mint, $amount, $fee, $to_amount) {
            $mint = new Mint();
            $mint->user_id = $this->nft->user_id;
            $mint->nft_id = $this->nft->nft_id;
            $mint->power = $this->nft->power;
            $mint->per_mint = $per_mint;
            $mint->amount = $amount;
            $mint->fee = $fee;
            $mint->to_amount = $to_amount;
            $mint->status = 'waiting';
            $mint->save();

            $this->nft->minted_days++;
            $this->nft->minted_amount = bcadd($this->nft->minted_amount, $amount, 8);
            $this->nft->save();
        });
    }
}
